package com.raindrop.rd.util;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author BillDowney
 * @date 2021/3/23 11:40
 */
public class BeanUtil {
    public static <T> byte[] objectToBytes(T obj) {
        byte[] bytes = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ObjectOutputStream sOut;
        try {
            sOut = new ObjectOutputStream(out);
            sOut.writeObject(obj);
            sOut.flush();
            bytes = out.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }

    @SuppressWarnings("unchecked")
    public static <T> T bytesToObject(byte[] bytes) {
        Object t;
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        ObjectInputStream sIn;
        try {
            sIn = new ObjectInputStream(in);
            t = sIn.readObject();
            if (t != null) {
                return (T) t;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        Aaa a = new Aaa();
        a.setText("啊实打实都");
        List<Aaa> list1 = new ArrayList<>();
        list1.add(a);
        byte[] bytes = objectToBytes(list1);
        List<Aaa> list2 = bytesToObject(bytes);
        list2.forEach(System.out::println);
    }

    static class Aaa implements Serializable {
        private String text;

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }

        @Override
        public String toString() {
            return "Aaa{" +
                    "text='" + text + '\'' +
                    '}';
        }
    }
}
